

/*往数据库里插入记录*/


import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class Demo04 {
    public static void main(String[] args) {
        //a
        //定义MYSQL数据源对象
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        //设置数据库的连接串url
        mysqlDataSource.setURL("");
        //设置用户名
        mysqlDataSource.setUser("root");
        //设置密码
        mysqlDataSource.setPassword("123456");
        //定义JDBC数据源对象
        DataSource dataSource = mysqlDataSource;


        //定义对象，方便之后释放资源
        //声明数据库连接对象
        Connection connection = null;
        //声明SQL语句的预处理对象（可以过滤掉非法字符-》通过这个预处理对象来解决注入问题
        PreparedStatement statement = null;
        //声明结果集对象
        ResultSet resultSet = null;
        //b
        //从a到b都是重复的代码，真正开始业务的是从 connection = dataSource.getConnection();这里开始的

        try {
            //1.获取数据库连接
            connection = dataSource.getConnection();
            //2.定义SQL语句
            String sql="insert into student(name,sno,age,gender,enroll_date,class_id) values (?,?,?,?,?,?)";
            //3.定义SQL预处理对象
            statement=connection.prepareStatement(sql);
            //4.接收用户输入
            Scanner scanner=new Scanner(System.in);
            String inputName=scanner.next();
            String inputSno=scanner.next();
            int inputAge=scanner.nextInt();
            byte inputGender=scanner.nextByte();
            String inputErollDate=scanner.next();
            long inputClassId=scanner.nextLong();
            //5.用真实数据替换占位符
            statement.setString(1,inputName);
            statement.setString(2,inputSno);
            statement.setInt(3,inputAge);
            statement.setByte(4,inputGender);
            statement.setString(5,inputErollDate);
            statement.setLong(6,inputClassId);
            //6.执行SQL
            int row=statement.executeUpdate();
            if(row==1){
                System.out.println("插入成功");
            }else{
                System.out.println("插入失败");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
